import {MAIN_RISK_TYPE} from '@/constants/options';
import { arrayUnique, groupBy, JSONParseFallback, map, simpleMerge } from '@/utils';
import { useContext } from 'react';
import { Context } from '.';
import { dutyValueMap } from './FIELDS';
import type from './type.json';

const create = () => JSON.parse(type);

const simpleClone = (data) => JSON.parse(JSON.stringify(data ?? null));

function mergeProductCode(productCode) {
  return {
    productAddVo: {
      productAttrVo: {
        productCode: productCode,
      },
      productInsureVo: {
        relationCode: productCode,
      },
      productSecurityVo: {
        relationCode: productCode,
      },
      preProductCode: productCode,
    },
    productRateVo: {
      productCode: productCode,
    },
  };
}

export function dutyData2Form(dataDutyValue) {
  if (!dataDutyValue) return null;
  const dutyValue = simpleClone(dataDutyValue);
  dutyValue.nextRule?.forEach((dutyRule) => {
    dutyRule.ruleValue = dutyRule.ruleValue.split(',');
    dutyRule.ruleSentence?.forEach((sentenceItem) => {
      // 去掉productCode
      // sentenceItem.dutyCode = sentenceItem.dutyCode.split('_')[1];

      sentenceItem.dutyValue = JSON.stringify(sentenceItem.dutyValue ?? dutyValueMap.selectable);

      // 附加责任项的 CheckboxGroup
      sentenceItem.rules = Object.keys(pick(sentenceItem, ['dutyName', 'dutyCode', 'dutyValue'])[1]);
      sentenceItem.rules = sentenceItem.rules.filter((k) => sentenceItem[k]);
    });
  });
  return dutyValue;
}

export function dutyForm2Data(formDutyValue, data) {
  if (!formDutyValue) return null;
  const { productCode = null } = data?.productAddVo?.productAttrVo ?? {};

  const dutyObject = simpleClone(formDutyValue);
  let dutyCodes = [productCode];
  dutyObject.dutyCode = productCode;
  dutyObject.dutyValue = JSON.parse(dutyValueMap.required);
  dutyObject.nextRule =
    dutyObject.nextRule?.map((ruleItem) => {
      let { ruleCode, ruleValue, ruleSentence } = ruleItem;
      ruleValue = ruleValue.join(',');
      ruleSentence =
        ruleSentence?.map((sentenceItem) => {
          let { dutyName, dutyCode, dutyValue, contArea, contPlanCode, rules, ...ruleObjects } = sentenceItem;

          ruleObjects = Object.fromEntries(
            map(ruleObjects, (rule, key) => {
              return [key, !rule?.values?.length || !rule?.name ? null : rule];
            }),
          );

          // 拼接productCode
          // dutyCode = `${productCode}_${dutyCode}`;
          dutyCode = `${dutyCode}`;
          dutyCodes.push(dutyCode);

          return {
            dutyName,
            dutyCode,
            dutyValue: JSON.parse(dutyValue ?? dutyValueMap.selectable),
            // contArea,
            // contPlanCode,
            ...ruleObjects,
          };
        }) ?? [];

      return {
        ruleCode,
        ruleValue,
        ruleSentence,
      };
    }) ?? [];

  console.log({ dutyObject });
  return [dutyObject, arrayUnique(dutyCodes).join(',')];
}

/** 字段回显处理 */
export function data2Form(respData) {
  console.log('data2Form: responseData', respData);
  const data = simpleClone(respData);
  const formData = simpleClone(data);
  const { productCode = null } = data?.productAddVo?.productAttrVo ?? {};

  /** productAttrVo.productAttrList */
  const attrList = data?.productAddVo?.productAttrVo?.productAttrList ?? [];
  const {
    duty: { value: duty } = {},
    dutyCodes: { value: dutyCodes } = {},
    muilt: { value: muilt } = {},
    paymentYearRule: { value: paymentYearRule } = {},
    paymentTypeRule: { value: paymentTypeRule } = {},
    guaranteedTypeRule: { value: guaranteedTypeRule } = {},
    guaranteedValue: { value: guaranteedValue } = {},
    // recognizeesType: { value: recognizeesType } = {},
    exemptions: { value: exemptions } = {},
    enterSocialSecurity: { value: enterSocialSecurity } = {},
    enterJobLevel: { value: enterJobLevel } = {},
    dutyFlag: { value: dutyFlag } = {},
    ...attrData
  } =
    attrList?.reduce(
      (ret, { attributeCode, attributeValue, attributeType }) => ({
        ...ret,
        [attributeCode]: {
          value: JSONParseFallback(attributeValue) ?? attributeValue ?? null,
          attributeType,
        },
      }),
      {},
    ) ?? {};
  console.log('data2form: duty', duty);
  formData.attributeData = attrData;
  formData.duty = dutyData2Form(duty);

  /** attributeCode: muilt premPay 保费缴费 */
  formData.premPay = [];
  muilt?.forEach((item) => {
    if (item.constraintAttribute?.[0].factor === 'age') {
      const [minAge, minAgeUnit] = item.constraintAttribute?.[0].value1?.split('_') ?? [null, null];
      const [maxAge, maxAgeUnit] = item.constraintAttribute?.[0].value2?.split('_') ?? [null, null];
      formData.premPay.push({
        ...item,
        minAge,
        minAgeUnit,
        maxAge,
        maxAgeUnit,
      });
    }
  });

  /** attributeCode: paymentYearRule 缴费年限规则 */
  formData.paymentYearRule = `${paymentYearRule ?? '1'}`;
  formData.paymentTypeRule = `${paymentTypeRule ?? '1'}`;
  formData.guaranteedTypeRule = `${guaranteedTypeRule ?? '1'}`;
  formData.enterSocialSecurity = `${enterSocialSecurity ?? '0'}`;
  formData.enterJobLevel = `${enterJobLevel ? '1' : '0'}`;
  formData.enterJobLevelValue = enterJobLevel;
  formData.dutyFlag = `${dutyFlag ?? '0'}`;;

  /** attributeCode: guaranteedValue 终身标记 */
  formData.guaranteedValue = guaranteedValue?.[0]?.code?.split('_')?.[0] ?? null;

  /** attributeCode: recognizeesType 多被保计划 */
  // formData.recognizeesType = recognizeesType ?? null;

  /** exemptions */
  formData.exemptions = exemptions ?? null;

  /** productRateVo.relationRateVoList.attachmentFormulaVoList */
  const { 1: masterFormulaList, ...dutyFormulaByDutyCode } = groupBy(
    data?.productRateVo?.relationRateVoList?.reduce((r, t) => [...r, ...(t?.attachmentFormulaVoList ?? [])], []) ?? [],
    (v) => {
      // 险种费率文件, A1 保费, A4 现金, A5 红利
      if (v.productCode === productCode) {
        return 1;
      } // 责任费率文件 用责任code作为key
      else {
        return v.productCode;
      }

      // 责任费率文件 用责任code作为key
      // if (v.productCode.startsWith(`${productCode}_`)) return
      // v.productCode.replace(`${productCode}_`, ''); 其他 return 2;
    },
  );
  // 险种费率文件 结构: { A1: [{}], A4: [{}], A5: [{}], ... }
  // 险种费率文件 用文件类型作为key
  formData.formula = groupBy(masterFormulaList ?? [], 'formulaType');

  // 医疗责任费率文件 结构: { [dutyCode]: [{}], ... }
  formData.dutyFormula = dutyFormulaByDutyCode;
  console.log(simpleClone(dutyFormulaByDutyCode));

  /** productAddVo.productClauseVoList 条款文件 */
  formData.clause = data?.productAddVo?.productClauseVoList ?? [];

  /** productAddVo.droolsRules 规则 */
  formData.droolsRules = data?.productAddVo?.droolsRules ?? [];

  console.log('data2Form: return formData', formData);
  return formData;
}

/** 表单提交处理 */
export function form2Data(formData, responseData) {
  const respData = simpleClone(responseData);
  const data = simpleClone(formData);
  console.log('form2Data: formData', data);
  console.log('form2Data: responseData', respData);
  const { productCode = null, productType } = data?.productAddVo?.productAttrVo ?? {};

  /** productRateVo.relationRateVoList.attachmentFormulaVoList */
  let attachmentFormulaVoList = [];

  /** productAddVo.productAttrVo.productAttrList */
  let productAttrList = Object.keys(formData.attributeData ?? {}).map((attributeCode) => {
    const { value, attributeType = 'BA' } = formData.attributeData[attributeCode];
    return {
      productCode,
      attributeCode,
      attributeType,
      attributeValue: `${typeof value === 'string' ? value : value ? JSON.stringify(value) : ''}`,
    };
  });

  /** duty */
  if (data.duty) {
    const [dutyData, dutyCodesData] = dutyForm2Data(data.duty, data);
    productAttrList.push(
      {
        productCode,
        attributeType: 'CAL',
        attributeCode: 'duty',
        attributeValue: JSON.stringify(dutyData),
      },
      data.duty && {
        productCode,
        attributeType: 'CAL',
        attributeCode: 'dutyCodes',
        attributeValue: dutyCodesData,
      },
    );
  }

  /** attributeCode: muilt premPay */
  let muilt = [];
  if (data.premPay?.length) {
    muilt.push(
      ...data.premPay.map((item) => ({
        coreCode: item.coreCode,
        paymentYears: item.paymentYears,
        guaranteedValue: item.guaranteedValue,
        paymentType: item.paymentType,
        pensionAge: item.pensionAge,
        constraintAttribute: [
          {
            factor: 'age',
            operator: 'GELE',
            value1: `${item.minAge}_${item.minAgeUnit}`,
            value2: `${item.maxAge}_${item.maxAgeUnit}`,
            value3: '',
            value4: '',
          },
        ],
      })),
    );
  }

  if (muilt.length) {
    productAttrList.push({
      productCode,
      attributeType: 'BA',
      attributeCode: 'muilt',
      attributeValue: JSON.stringify(muilt),
    });
  }
  /** !END muilt */

  /** attributeCode: paymentYearRule 缴费年限规则 */
  if ((formData.paymentYearRule || '1') !== '1') {
    productAttrList.push({
      productCode,
      attributeType: 'BA',
      attributeCode: 'paymentYearRule',
      attributeValue: `${formData.paymentYearRule}`,
    });
  }
  if ((formData.paymentTypeRule || '1') !== '1') {
    productAttrList.push({
      productCode,
      attributeType: 'BA',
      attributeCode: 'paymentTypeRule',
      attributeValue: `${formData.paymentTypeRule}`,
    });
  }
  if ((formData.guaranteedTypeRule || '1') !== '1') {
    productAttrList.push({
      productCode,
      attributeType: 'BA',
      attributeCode: 'guaranteedTypeRule',
      attributeValue: `${formData.guaranteedTypeRule}`,
    });
  }

  /** attributeCode: guaranteedValue 终身标记 */
  if (formData.guaranteedValue != null) {
    productAttrList.push({
      productCode,
      attributeType: 'BA',
      attributeCode: 'guaranteedValue',
      attributeValue: JSON.stringify([{ code: `${formData.guaranteedValue}_A`, name: '终身' }]),
    });
  }

  productAttrList.push(
    {
      productCode,
      attributeType: 'BA',
      attributeCode: 'enterSocialSecurity',
      attributeValue: formData.enterSocialSecurity,
    },
    {
      productCode,
      attributeType: 'BA',
      attributeCode: 'enterJobLevel',
      attributeValue: formData.enterJobLevel === '1' ? JSON.stringify(formData.enterJobLevelValue) : null,
    }
  );

  if (productType !== MAIN_RISK_TYPE) {
    productAttrList.push({
      productCode,
      attributeType: 'BA',
      attributeCode: 'dutyFlag',
      attributeValue: formData.dutyFlag || '0',
    })
  }

  /** attributeCode: recognizeesType 终身标记 */
  /*if (formData.recognizeesType != null) {
   productAttrList.push({
   productCode,
   attributeType: 'BA',
   attributeCode: 'recognizeesType',
   attributeValue: `${formData.recognizeesType}`,
   });
   }*/

  /** 险种费率 */
  Object.keys(formData.formula ?? {}).forEach((fileType) => {
    const [value] = formData.formula[fileType] ?? [];
    if (!value) return;
    attachmentFormulaVoList.push(
      simpleMerge({}, value, {
        attachment: value.attachment
          ? {
              relationCode: productCode,
              fileType: fileType,
            }
          : null,
        costCalculateFormula: {
          productCode,
          formulaType: fileType,
        },
        formulaType: fileType,
        list:
          value.list?.map(() => ({
            relationCode: productCode,
          })) ?? null,
        productCode,
        productId: productCode,
      }),
    );
  });

  /** 责任费率 */
  Object.keys(formData.dutyFormula ?? {}).forEach((dutyCode) => {
    const [value] = formData.dutyFormula[dutyCode] ?? [];
    if (!value) return;
    // const relationCode = `${productCode}_${dutyCode}`;
    const relationCode = `${dutyCode}`;

    attachmentFormulaVoList.push(
      simpleMerge({}, value, {
        attachment: {
          relationCode: relationCode,
          fileType: 'A1',
        },
        costCalculateFormula: {
          productCode: relationCode,
          formulaType: 'A1',
        },
        formulaType: 'A1',
        productCode: relationCode,
        productId: relationCode,
      }),
    );
  });

  let productClauseVoList = formData.clause ?? [];
  let droolsRules =
    formData.droolsRules?.map((v) => ({
      ruleSentence: v.ruleSentence,
      ruleResolveWay: 'M',
      attributeRulePurpose: 'M',
      sourceCode: productCode,
    })) ?? [];

  if (respData) {
    // merge 对数组没有全量更新 所以先删除
    delete respData.productRateVo;
    delete respData.productAttrVo?.productAttrList;
    delete respData.productAddVo?.productClauseVoList;
    delete respData.productAddVo?.droolsRules;
  }

  const requestData = simpleMerge(
    create(),
    respData,
    { productAddVo: data.productAddVo },
    {
      productAddVo: {
        productClauseVoList,
        droolsRules,
        productAttrVo: {
          productAttrList,
        },
        productInsureVo: {
          minCoverageLimit: data.productAddVo?.productInsureVo?.minPremiumLimit ?? null,
          maxCoverageLimit: data.productAddVo?.productInsureVo?.maxPremiumLimit ?? null,
        },
      },
      productLiabilityVo: null,
      productRateVo: {
        relationRateVoList: [
          {
            attachmentFormulaVoList,
            riskAmountFormulaList: [],
            relationCode: productCode,
            relationId: null,
            relationType: 'P',
          },
        ],
        productCode: productCode,
      },
    },
    mergeProductCode(productCode),
  );

  console.log('form2Data: return requestData', requestData);
  return requestData;
}

export function createDutyItem({ liabilityCode, liabilityName }) {
  return {
    dutyCode: liabilityCode,
    dutyName: liabilityName,
    nextRule: [],
    deductible: null,
    conceitRatio: null,
  };
}

export function useProductCode() {
  return useContext(Context).productCode;
}
